/*
 * 管理员后台js 开启严格模式
 */
"use strict";
const js_configurg = {
    loading_time_out: 0,//15秒 loading等待时间，超过此时间将自动取消loading
}

// 登录
function login() {
    const form = document.loginForm;
    form.userName.focus();
    //返回验证码
    const checkNumImg = '#checkNumImg';
    $(checkNumImg).on('click', function () {
        $(this).attr('src', `${root}library/libData.html?type=proveImg&random=${Math.random()}`);
    });
    //按下回车键时，触发登录按钮
    const subButton = '[subButton=yes]';
    $(document).on('keyup', function (event) {
        if (event.keyCode === 13) {
            $(subButton).click();
        }
    });
}


/***客户管理-跟进记录快捷按钮***/
function textQuick(obj) {
    document.followForm.text.value = $(obj).html();
}

// 验证表单数据
function validate(obj) {
    const validation = {
        userName: '用户名',
        password: '密码',
        prove: '验证码',
        company: '企业名称',
    };

    const name = $(obj).attr('name');
    let errorTpl = '';

    if ($(obj).val().trim().length <= 0) {
        errorTpl = `<span class='errormsg'>请输入${validation[name]}</span>`;
        $(obj).after(errorTpl);
    } else {
        $(obj).nextAll('.errormsg').remove();
    }

    let flag = true;
    const fields = Object.keys(validation);
    const inputs = fields.map((field) => $(`[name="${field}"]`));
    for (let i = 0; i < inputs.length; i++) {
        const input = inputs[i];
        const value = input.val() ? input.val().trim() : '';
        if (value.length <= 0) {
            flag = false;
            break;
        }
    }
    if (flag) {
        const submitBtn = $('#login-submit');
        if (!submitBtn.hasClass('disabled')) {
            submitBtn.addClass('disabled');
        }
    }
}

/** home 日期查询 */
function searchLine(value, fun, cla = 'homepage') {
    $.post(root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun, {
        startMoon: value
    }, function (res) {
        let obj = '#' + fun + 'Html';
        $(obj).empty().append(res.html);
    }, 'json')
}

/***iframe框架***/
//点击主页
function homepage() {
    //iframe切换
    $("[iframeName]").css("display", "none");
    $("[iframeName=主页]").css("display", "block");
    //顶部页卡切换
    $("#iframeTitle > ul > li").removeClass("iframeTitleNow");
    $("#homepage").addClass("iframeTitleNow");
    //清理左侧导航高亮选择效果
    $("[iframeHref]").removeClass("frameLeftHover");
}

//顶部导航向左移动
function pageLeft() {
    var widthTitle = parseFloat($("#iframeTitle").css("width"));
    var widthUl = parseFloat($("#iframeTitle > ul").css("width"));
    var left = parseFloat($("#iframeTitle > ul").css("left"));
    if (left < 0) {
        left += 137;
        $("#iframeTitle > ul").css("left", left + "px");
    }
    //left参数值可能已改变
    if (left >= 0) {
        $("#pageLeft > img").attr("src", root + "img/control/pageLeft.svg");
    }
    if (widthUl + left > widthTitle) {
        $("#pageRight > img").attr("src", root + "img/control/pageRightLight.svg");
    }
    console.log("widthTitle：" + widthTitle + ",widthUl:" + widthUl + ",left:" + left);
}

//顶部导航向右移动
function pageRight() {
    var widthTitle = parseFloat($("#iframeTitle").css("width"));
    var widthUl = parseFloat($("#iframeTitle > ul").css("width"));
    var left = parseFloat($("#iframeTitle > ul").css("left"));
    if (widthUl + left > widthTitle) {
        left -= 137;
        $("#iframeTitle > ul").css("left", left + "px");
    }
    //left参数值可能已改变
    if (left < 0) {
        $("#pageLeft > img").attr("src", root + "img/control/pageLeftLight.svg");
    }
    if (widthUl + left <= widthTitle) {
        $("#pageRight > img").attr("src", root + "img/control/pageRight.svg");
    }
    console.log("widthTitle：" + widthTitle + ",widthUl:" + widthUl + ",left:" + left);
}

//缩放左侧菜单
function shrink(obj) {
    var left = root + "img/control/moveLeft.svg";
    var right = root + "img/control/moveRight.svg";
    var now = $(obj).children("img").attr("src");
    if (now === left) {
        $(obj).children("img").attr("src", right);
        $(obj).children("img").attr("title", "显示左侧菜单");
        $("#frameLeft, #adLogo").hide();
        $("#homepage, #pageLeft, #iframeTitle, #menu, #shrink, #frameRight, .primaryMenu").css({
            "left": "-=165px"
        });
    } else {
        $(obj).children("img").attr("src", left);
        $(obj).children("img").attr("title", "隐藏左侧菜单");
        $("#frameLeft, #adLogo").show();
        $("#homepage, #pageLeft, #menu, #iframeTitle, #shrink, #frameRight, .primaryMenu").css({
            "left": "+=165px"
        });
    }
}


function menu() {
    // 备选方式
    // $("#appendBox").find('.primaryMenu').show();
}

// 加载二维码函数
function loadQRcode() {
    // 从后台返回data
    const data = '做企业管理软件，找雨木科技。\n\n 技术联系电话：023-88692248 18581286862'
    let qrSrc = root + 'pay/wxpay/wxScanPng?url=' + data
    $('#login-qr').attr('src', qrSrc)
}

$(function () {
    Date.prototype.Format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    // 登录账号和二维码切换
    $(document).on('click', "#loginSwitch", function () {
        // 暂时隐藏
        // return false
        let current = $(this).attr('current'), imgSrc = ''
        if (current === 'account') {
            $('#login-main-account, .login-bottom').hide()
            $('#login-main-qr').show()
            $(this).attr('current', 'QRcode')
            imgSrc = root + 'img/websiteImg/pc_login.png'
            let did = $("input[name='did']").val();
            // loadQRcode()
            // let url = encodeURI(root+'control/qyLoginClass?did='+did);
            let css = encodeURI(root + 'static/stylesheet/login.css');
            $.post(root + 'library/libData.html?type=getPara', {did: did}, function (res) {
                new WwLogin({
                    "id": "login-main-qr",
                    "appid": res.appid,
                    "agentid": res.agentid,
                    "redirect_uri": res.url,
                    "state": res.nonstr,
                    "href": css,
                    "lang": "zh",
                });
            }, 'json')

        } else {
            $(this).attr('current', 'account')
            $('#login-main-account, .login-bottom').show()
            $('#login-main-qr').hide()
            imgSrc = root + 'img/websiteImg/qr_login.png'
        }
        $(this).find('img').attr('src', imgSrc)
    });

    // 主菜单显隐藏
    $("#menu,.primaryMenu").hover(function () {
        $('.primaryMenu').show()
    }, function () {
        $('.primaryMenu').hide()
    })

    // 主菜单 鼠标事件
    $(".primaryMenu li").hover(function () {
        $(this).find('img').css("visibility", "inherit")
    }, function () {
        let obj = $(this).find('img')
        if (!obj.hasClass('clip-selected')) {
            obj.css("visibility", "hidden")
        }
    })

    $("#coid").on('change', function () {
        let coid = $(this).val();
        if (coid.length <= 0) {
            msg('请选择账套', 'error');
        } else {
            let con = setTimeout(function () {
                $("#loading", parent.document).hide();
            }, lib_configurg.loading_time_out);
            $("#loading", parent.document).show();
            $.post(root + "control/adIndex.html?cla=homepage&fun=updateCoid", {
                'coid': coid
            }, function (data) {
                if (data.warn === 2) {
                    href('control/adIndex.html');
                } else {
                    msg(data.warn, 'error');
                }
                $("#loading", parent.document).hide();
                clearTimeout(con);
            }, "json")
        }
    })
    // 切换主菜单
    $(document).on('click', '.primaryMenu li', this, function () {
        let menu = $(this).find('span').html()
        if (menu.length <= 0) {
            warn('一级菜单错误')
        } else {
            $.post(root + "control/adIndex.html?cla=homepage&fun=getMenuTwo", {
                'menu': menu
            }, function (data) {
                if (data.warn === 2) {
                    //切换到主页，并显示一级菜单的主页内容
                    let home = $('[iframename=主页]');
                    let preMenu = home.data('menu') ? home.data('menu') : '';
                    $.post(root + "control/adIndex.html?cla=homepage&fun=isRefresh", {
                        menuType: menu, preMenu: preMenu
                    }, function (res) {
                        if (res) {
                            homepage();
                            home.data('menu', menu);
                            home.attr('src', root + 'control/adIndex.html?cla=homepage&fun=home&menuType=' + menu);
                        }
                        if (menu === '供应链' || menu === '生产制造' || menu === '财务会计' || menu === '供應鏈' || menu === '生產製造' || menu === '財務會計') {
                            $("#coid").show();
                        } else {
                            $("#coid").hide();
                        }
                        $(document).find('#frameLeft > ul').html(data.html)
                    }, 'json')
                } else {
                    warn(data.warn)
                }
            }, "json")
        }
    })

    // 设置主菜单
    $(document).on('click', '.primaryMenu li img.clip', this, function () {
        let menu = $(this).attr('data-title')
        if (menu.length <= 0) {
            warn('一级菜单错误')
        } else {
            $.post(root + "control/adIndex.html?cla=homepage&fun=setMenu", {
                'menu': menu
            }, function (data) {
                if (data.warn === 2) {
                    window.location.reload()
                } else {
                    warn(data.warn)
                }
            }, "json")
        }
    })

    // 会员中心角标
    // $("#user").hover(function () {
    //     $('.userList').show()
    // }, function () {
    //     $('.userList').hover(function () {
    //         $('.userList').show()
    //     }, function () {
    //         $('.userList').hide()
    //     })
    // })
    $("#user").bind('click', function () {
        let display = $(".userList").css('display');
        if (display === 'none') {
            $('.userList').show()
        } else {
            $('.userList').hide()
        }
    })

    // 申请单状态
    $("#record").hover(function () {
        $('.stateBlock').show()
    }, function () {
        $('.stateBlock').hover(function () {
            $('.stateBlock').show()
        }, function () {
            $('.stateBlock').hide()
        })
    })

    // 表单多选
    $("#body").on('click', ".winAuto .tableMany tr", function () {
        let radio = $(this).find("td:first").find("input[type='radio']")
        let checkbox = $(this).find("td:first").find("input[type='checkbox']")
        if (radio.length > 0) {
            radio.prop("checked", true)
        } else if (checkbox.length > 0) {
            if (checkbox.is(":checked")) {
                checkbox.prop('checked', false)
            } else {
                checkbox.prop('checked', true)
            }
        }
    })
    // 自定义字段显示
    $(document).on('click', "#fieldSetting", function (that) {
        let panel = $(that.target).next(".field-panel")
        const display = panel.css('display')
        if (display === 'none') {
            panel.show()
        } else {
            panel.hide()
        }
    })
    // 自定义字段全选
    $(document).on('click', '[name="checkAllField"]', function () {
        if ($(this).is(":checked")) {
            $("[name='fields[]']").prop('checked', true)
        } else {
            $("[name='fields[]']").prop('checked', false)
        }
        syncData($('[pagediv]').attr('pagediv'))
    })

    $(document).on('click', "[name='fields[]']", function () {
        syncData($('[pagediv]').attr('pagediv'))
    })

    $(document).on('click', '#body', function (e) {
        let target = $("#fieldPanel")
        if (target.length > 0) {
            let click_target = $("#fieldSetting")
            let disply = target.css('display')
            if (!target.is(e.target) && target.has(e.target).length === 0 && click_target.has(e.target).length === 0 && disply !== 'none' && !click_target.is(e.target)) {
                target.hide();
                location.reload();
            }
        }
    })

    // 同步数据
    function syncData(ele) {
        const $element = $('[pagediv="' + ele + '"]')
        const formData = $element.find('[searchformhtml] > form').serialize()
        $.post(root + 'control/adIndex.html?cla=homepage&fun=setField', formData, function (res) {
            if (res.code === 0) {
                msg(res.warn, 'error')
            }
        }, 'json')
    }

    // 界面排序
    $(document).on('click', '[sort-key] > span:not(".drag")', function () {
        // 判断是否有表格固定框架
        const has = $(document).find('.fixed-thead').length
        const ascObj = $(this).parent().find('.table-sort-asc'),
            descObj = $(this).parent().find('.table-sort-desc')

        let table = (has === 1) ? $(this).closest('.fixed-thead').find('.fixed-thead-body > table').eq(0) : $(this).parents('table').eq(0)
        let rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).parent().index()))
        this.asc = !this.asc
        if (!this.asc) {
            rows = rows.reverse()
            ascObj.removeClass('table-sort-asced')
            descObj.addClass('table-sort-desced')
        } else {
            ascObj.addClass('table-sort-asced')
            descObj.removeClass('table-sort-desced')
        }
        $(this).parent().siblings().find('i').removeClass('table-sort-asced table-sort-desced')
        table.children('tbody').empty().html(rows)
    })

    function comparer(index) {
        return function (a, b) {
            let valA = getCellValue(a, index), valB = getCellValue(b, index)
            return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
        }
    }

    function getCellValue(row, index) {
        return $(row).children('td').eq(index).text();
    }

    //分类选择器
    $(document).on('click', '#layerBut', this, function () {
        let parent = $(this).parents('span#type-box'),
            name = $(this).data('name'),
            obj = parent.find('[name="' + name + '"]'),
            id = rand()
        if (obj.length > 0) {
            id = obj.attr('id')
        } else {
            let tpl = `
            <input id='` + id + `' type='hidden' name='materialTypeId'>`
            parent.append(tpl)
        }
        let params = {}

        // 类型
        switch ($(this).attr('id')) {
            case 'layerBut'://单独作为员工选择器时
                params = {
                    id: id,
                    all: true,
                    other: 'selector',
                }
                break;
        }
        // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
        layer('examine', 'materialTypeTree', params)
        $(this).find('.placeholder').remove()
    })

})

/**
 * 页面加载滚动到上次定位的位置
 */
function initScrollPosition() {
    // 判断当前窗口是否在 iframe 中
    if (window.parent !== window) {
        var frameSrc = window.frameElement.src; // 获取当前窗口所在的iframe的src属性
        var scrollPosition = sessionStorage.getItem('scrollPosition_'+frameSrc);
        console.log('scrollTop：'+scrollPosition)
        if (scrollPosition !== null) {
            $(window.frameElement).contents().find('.fixed-thead-body').scrollTop(scrollPosition);
        }
    }
}
/**
 * 表格宽度调整
 */
function loadTableTool() {
    let isdown = false, beginx = 0, oldwidth = 0, parent
    const has = $(document).find('.fixed-thead').length
    const obj = (has === 1) ? ".fixed-thead-head > .tableMany > thead > tr" : ".tableMany > thead > tr"
    // 鼠标抬起
    $(document).mouseup(function (that) {
        if ($(obj).length > 0) {
            if (($.contains($(obj)[0], that.target) || $(obj)[0] === that.target)) {
                isdown = false
                const field = $(parent).attr('sort-key'),
                    width = !isNaN($(parent).attr('width')) ? $(parent).attr('width') : 80
                if (field && width !== oldwidth && !isNaN(width)) {
                    let string = $("[name='listForm']").serialize()
                    if (string.indexOf('fields') < 0) {
                        msg('请先设置需显示的列', 'error')
                    } else {
                        if (parseFloat(oldwidth) === parseFloat(width)) {
                            return false
                        }
                        string += '&' + field + '=' + parseFloat(width)
                        $.post(root + 'control/adIndex.html?cla=homepage&fun=setField', string, function (res) {
                            if (res.code === 0) {
                                msg(res.warn, 'error')
                            }
                        }, 'json')
                    }
                }
            }
        }
    })
    // 鼠标点击
    $(document).mousedown(function (that) {
        if ($(obj).length > 0) {
            if (($.contains($(obj)[0], that.target) || $(obj)[0] === that.target)) {
                isdown = true
                beginx = parseFloat(that.pageX)
                parent = that.target.offsetParent
                oldwidth = parseFloat($(parent).attr('width') ? $(parent).attr('width') : parent.clientWidth)
            }
        }
    })
    // 鼠标移动
    $(document).mousemove(function (that) {
        if ($(obj).length > 0) {
            if (($.contains($(obj)[0], that.target) || $(obj)[0] === that.target) && isdown) {
                const fixedObj = $(document).find('.fixed-thead > .fixed-thead-body > table')
                parent.width = oldwidth + parseFloat(that.pageX) - beginx
                if (fixedObj.length === 1) {
                    $(document).find("[sort-key='" + $(parent).attr('sort-key') + "']").last().width(oldwidth + parseFloat(that.pageX) - beginx)
                }
            } else {
                isdown = false
            }
        }
    })
}

//点击左侧导航
function iframeHref(obj) {
    //赋值
    var url = $(obj).attr("iframeHref");
    var name = $(obj).attr("title");
    var titleName = $("[iframeMenuName=" + name + "]").html();
    var menuOne = $(obj).attr('menu_one'); //一级菜单
    var menuTwo = $(obj).attr('menuparent'); //二级菜单
    //检查此页卡是否存在
    if (titleName) {
        iframeTitle(titleName);
    } else {
        //添加iframe
        $("[iframeName]").css("display", "none");
        $("#frameRight").append(`<iframe scrolling='yes' frameborder='0' class='iframe' iframeName='${name}' src='${url}'></iframe>`);
        //延长ul
        $("#iframeTitle > ul").css({
            width: "+=137px"
        });
        //添加顶部页卡
        $("#homepage").removeClass("iframeTitleNow");
        $("#iframeTitle > ul > li").removeClass("iframeTitleNow");
        var widthTitle = parseFloat($("#iframeTitle").css("width"));
        var bigNum = parseInt(widthTitle / 137) - 2;
        var length = $("#iframeTitle > ul > li").length;
        var iframeTitleNow = `<li class="iframeTitleNow"><div title="${name}" iframe_menu_one="${menuOne}" iframe_menu_two="${menuTwo}" iframeMenuName="${name}" goback="${name}">${name}</div><div class="iframeClose" onclick="iframeClose(this)">×</div></li>`;
        if (length > bigNum) {
            $("#iframeTitle > ul > li:eq(" + bigNum + ")").after(iframeTitleNow);
        } else {
            $("#iframeTitle > ul").append(iframeTitleNow);
        }
        //修正左侧翻页箭头
        var widthUl = parseFloat($("#iframeTitle > ul").css("width"));
        var left = parseFloat($("#iframeTitle > ul").css("left"));
        if (widthUl + left > widthTitle) {
            $("#pageRight > img").attr("src", root + "img/control/pageRightLight.svg");
        }
    }
    //高亮显示左侧当前导航
    $("[iframeHref]").removeClass("frameLeftHover");
    $(obj).addClass("frameLeftHover");
}

// 关闭页卡
function iframeClose(obj) {
    var name = $(obj).prev().html();
    var goBack = $("[iframeName='" + name + "']").attr('goback'); //检查是否存在高亮的顶部页卡
    // 缩短ul
    $("#iframeTitle > ul").css({
        width: "-=137px"
    });
    // 多个iframe删除
    $("[goback='" + name + "']").remove();
    $("[iframeName='" + name + "']").remove();
    $(obj).parent().remove(); //删除顶部页卡
    // 判断上级是否存在
    if (goBack) {
        iframeTitle(goBack, 'top')
    } else {
        $("[iframeName=主页]").css("display", "block"); //显示我的桌面iframe
        $("#homepage").addClass("iframeTitleNow"); //高亮我的桌面顶部页卡
        $("[iframeHref]").removeClass("frameLeftHover"); //清理左侧导航高亮选择效果
    }
    //修正右侧翻页箭头
    fixRightArrow()
}

//修正右侧翻页箭头
function fixRightArrow() {
    var _$ = window.top.$
    var widthTitle = parseFloat(_$("#iframeTitle").css("width"));
    var widthUl = parseFloat(_$("#iframeTitle > ul").css("width"));
    var left = parseFloat(_$("#iframeTitle > ul").css("left"));
    if (widthUl + left <= widthTitle) {
        _$("#pageRight > img").attr("src", root + "img/control/pageRight.svg");
    }
}

// 关闭当前悬浮页面
function iframeReturnClose(obj, name) {
    var _$ = window.top.$
    // 关闭当前页，回到上层页
    var iframe = _$("[iframeName='" + name + "']")
    var goBack = iframe.attr('goback'); //上级页面
    var liObj = _$("#iframeTitle").find('.iframeTitleNow').find('[iframemenuname]')
    liObj.attr('goback', liObj.attr('iframemenuname'))
    // 移除 选项卡 移除页面
    iframe.remove()
    _$("#frameRight [goback='" + goBack + "']").remove();
    // liObj.remove()
    // 回到上级页面
    if (goBack.length > 0) {
        // _$("[iframeName='" + goBack + "']").css("display", "block");
        // let beforeFrame = _$("#frameRight [goback='" + goBack + "']");
        // console.log(beforeFrame)
        // if (beforeFrame.length >0){
        //     beforeFrame.css("display", "block");
        // }else{
        //     console.log('列表')
        //
        // }
        _$("[iframeName='" + goBack + "']").css("display", "block");
    } else {
        _$("[iframeName=主页]").css("display", "block"); //显示我的桌面iframe
        _$("#homepage").addClass("iframeTitleNow"); //高亮我的桌面顶部页卡
        _$("[iframeHref]").removeClass("frameLeftHover"); //清理左侧导航高亮选择效果
    }
    //修正右侧翻页箭头
    fixRightArrow()
}

function cls() {
    console.clear()
}

function log(obj) {
    console.log(obj)
}

//页卡切换函数
function iframeTitle(name, posititon = null) {
    //iframe切换
    $("[iframeName]").css("display", "none");
    $("[iframeName='" + name + "']").css("display", "block");
    //顶部页卡切换
    $("#homepage").removeClass("iframeTitleNow");
    $("#iframeTitle > ul > li").removeClass("iframeTitleNow");
    if (posititon != 'top') {
        $("[iframeMenuName='" + name + "']").parent().addClass("iframeTitleNow");
    } else {
        $("[goback='" + name + "']").parent().addClass("iframeTitleNow");
        // 菜单跟踪
        //顶部切换时
        let iframemenuname = $("[iframemenuname='" + name + "']");
        let menuOne = iframemenuname.attr('iframe_menu_one');
        let menuTwo = iframemenuname.attr('iframe_menu_two');
        let left_three_menu = $("li[menuparent='" + menuTwo + "'][title='" + name + "']"); //三级菜单对象
        let display = left_three_menu.css('display');
        if (!display) {
            if (menuOne !== undefined && menuOne) {
                //另一个一级菜单中
                $.post(root + "control/adIndex.html?cla=homepage&fun=getMenuTwo", {
                    'menu': menuOne
                }, function (data) {
                    if (data.warn === 2) {
                        if (menuOne === '产供销存' || menuOne === '财务会计') {
                            $("#coid").show();
                        } else {
                            $("#coid").hide();
                        }
                        $(document).find('#frameLeft > ul').html(data.html);
                        left_three_menu = $("li[menuparent='" + menuTwo + "'][title='" + name + "']"); //三级菜单对象
                        //二级菜单滑动
                        $("[menuParent=" + menuTwo + "]").slideToggle();
                        display = left_three_menu.css('display');
                        let obj = $("li[menuone='" + menuTwo + "']"); //二级菜单对象
                        switchTab(name, display, obj)
                    } else {
                        warn(data.warn)
                    }
                }, "json")
            }
        } else {
            //都在当前一级菜单中
            if (display === 'none') {
                //二级菜单滑动
                $("[menuParent=" + menuTwo + "]").slideToggle();
                let obj = $("li[menuone='" + menuTwo + "']"); //二级菜单对象
                switchTab(name, 'list-item', obj)
            }
        }
    }
}

/**
 * 切换箭头及切换左边导航高亮
 * @param name
 * @param display
 * @param obj
 */
function switchTab(name, display, obj) {
    //判断箭头
    if (display == 'none') {
        //如果第三级菜单未显示出来，则是隐藏状态
        var newImg = root + "img/images/triangleRight.png";
    } else {
        var newImg = root + "img/images/triangleDown.png";
    }
    obj.children("img").attr("src", newImg);
    //切换左侧导航
    var src = $("[iframeName='" + name + "']").attr("src");
    $("[iframeHref]").removeClass("frameLeftHover");
    $("[iframeHref='" + src + "']").addClass("frameLeftHover");
}

//左侧菜单点击事件~一级菜单
function menuOne(obj) {
    //重置箭头和菜单
    $("[menuParent]").slideUp();
    $("[menuone]").children("img").attr("src", root + "img/images/triangleRight.png");
    //二级菜单滑动
    let menuTwo = $("[menuParent=" + $(obj).attr("menuOne") + "]");
    if (menuTwo.css('display') === "none") {
        menuTwo.slideDown();
        $(obj).children("img").attr("src", root + "img/images/triangleDown.png");
    }
}

/*
 * iframe中新增顶层页卡
 *
 * 目的：系统中点击某些按钮时需要保留当前页面状态，并打开一个新的页面呈现用户需求。
 * 方法：触发本函数时，系统在adIndex.php创建一个新的iframe，即页卡。
 * 参数：name为顶层页卡名称，url为页卡的路径。
 */
function newIframe(name, url, iframe_menu_one = '', iframe_menu_two = '') {
    var parentDocument = window.parent.document
    var goBack = $(parentDocument).find('.iframeTitleNow > div').html() ? $(parentDocument).find('.iframeTitleNow > div').html() : '主页'
    if (name == "") {
        warn("在iframe中新增顶层iframe时name为空");
        return false
    } else if (url == "") {
        warn("在iframe中新增顶层iframe时url为空");
        return false
    } else {
        let short_url = url.substring(0, url.indexOf("&fun"));

        let iframeObj = $("[iframename='" + name + "']", parentDocument);

        var titleName = iframeObj.attr('iframename');
        if (titleName === name) {
            $("[iframeName='" + name + "']", parentDocument).attr("src", url);
            //iframe切换
            $("[iframeName]", parentDocument).css("display", "none");
            iframeObj.css("display", "block");
            $("#iframeTitle > ul > li", parentDocument).removeClass("iframeTitleNow");

            //顶部导航栏选中状态
            let iframemenuname = name;
            let backName = iframeObj.attr('goback');
            if (backName && backName !== 'undefined') {
                iframemenuname = backName;
            }
            let topTab = $("[iframemenuname='" + iframemenuname + "']", parentDocument);
            if (topTab.length > 0) {
                topTab.parent("li").addClass("iframeTitleNow");
            }
        } else {
            let iframename = $('.iframeTitleNow', parentDocument).children('[iframemenuname]').attr('iframemenuname');
            let urlNow = $("iframe[iframename='" + iframename + "']", parentDocument).attr('src');
            if (urlNow) {
                urlNow = urlNow.substring(0, urlNow.indexOf('&fun'))
            }
            if (short_url === urlNow) {
                //如果需要跳转的类跟当前打开页卡的类一致，则在当前页打开，否则另开页卡
                // 共用上级页面名称 ，先隐藏所有上级页面
                $("[iframeName]", parentDocument).css("display", "none");
                $("#frameRight", parentDocument).append(`<iframe scrolling="yes" frameborder="0" class="iframe" iframeName="${name}" src="${url}" goback="${goBack}" onload="iframeLoaded(this, '${name}')"></iframe>`);
            } else {
                //添加iframe
                $("[iframeName]", parentDocument).css("display", "none");
                $("#frameRight", parentDocument).append("<iframe scrolling='yes' frameborder='0' class='iframe'   iframeName='" + name + "' src='" + url + "'></iframe>");
                //延长ul
                $("#iframeTitle > ul", parentDocument).css({width: "+=137px"});
                //添加顶部页卡
                $("#homepage", parentDocument).removeClass("iframeTitleNow");
                $("#iframeTitle > ul > li", parentDocument).removeClass("iframeTitleNow");
                var widthTitle = parseFloat($("#iframeTitle", parentDocument).css("width"));
                var bigNum = parseInt(widthTitle / 137) - 2;
                var length = $("#iframeTitle > ul > li", parentDocument).length;
                var iframeTitleNow = "<li class='iframeTitleNow'><div title='" + name + "' iframe_menu_one='" + iframe_menu_one + "' iframe_menu_two='" + iframe_menu_two + "'  iframeMenuName='" + name + "' >" + name + "</div><div class='iframeClose' onclick=\"iframeClose(this)\">×</div></li>";
                if (length > bigNum) {
                    $("#iframeTitle > ul > li:eq(" + bigNum + ")", parentDocument).after(iframeTitleNow);
                } else {
                    $("#iframeTitle > ul", parentDocument).append(iframeTitleNow);
                }
            }

        }

        $('.iframeTitleNow', parentDocument).children('[iframemenuname]').attr('goback', name)

        //切换左侧导航
        var src = $("[iframeName='" + name + "']", parentDocument).attr("src");
        $("[iframeHref]", parentDocument).removeClass("frameLeftHover");
        $("[iframeHref='" + src + "']", parentDocument).addClass("frameLeftHover");
        if (iframe_menu_one && iframe_menu_two) {
            //切换页卡
            iframeTitle(name, 'top');
        }
    }
}

// 动态加载
function iframeLoaded(obj, name) {
    let returnHtml = `<div id="close" onclick="iframeReturnClose(this, '${name}')"><img title="关闭" src="${root}img/control/close.svg" iframeName="${name}"></div>`
    let body = $(obj).contents()
    let ele = body.find("#header").find('#renovate')
    if (ele.length > 0) {
        ele.before(returnHtml)
        body.find('#renovate, .onion').css('left', '+=40')
    }
}


/*顶部导航位置挪动*/
function moveMenu() {
    //初始化
    var div = "#iframeTitle > ul > li > div:first-of-type"; //点击区域
    var li = "#iframeTitle > ul > li"; //移动区域
    //按下鼠标
    $(document).on("mousedown", div, function (e) {
        //参数准备
        var ev = e || event;
        var startX = ev.clientX; //鼠标初始横坐标
        var thisli = $(this).parent(); //选中的li标签
        var width = thisli.outerWidth(true); //包含margin，border，padding的li标签宽度
        var length = $(li).length; //li标签的数量
        var index = thisli.index();
        var left = width * index; //此li标签的左侧间距，也是占位空白标签初始位置
        var name = $(this).attr("goback");
        //切换页卡
        iframeTitle(name, 'top');
        //切换左侧导航
        var src = $("[iframeName='" + name + "']").attr("src");
        $("[iframeHref]").removeClass("frameLeftHover");
        $("[iframeHref='" + src + "']").addClass("frameLeftHover");
        //占位空白标签效果
        $("<li class='empty'></li>").insertBefore(thisli);
        //将选中的li标签放在最后，方便insertBefore
        thisli.insertAfter(li + ":eq(" + length + ")");
        //将选中的li标签悬浮，方便跟随鼠标挪动
        thisli.css({
            "position": "absolute", "top": "0", "left": left
        });
        //鼠标移动
        document.onmousemove = function (m) {
            //获取参数
            var mv = m || event;
            var endX = mv.clientX; //当前鼠标横坐标
            //计算值
            var moveX = endX - startX; //鼠标按下后移动的距离
            var winLeft = left + moveX; //移动后此li标签的左侧距离
            //菜单移动效果
            thisli.css({
                "left": winLeft + "px"
            });
            //占位空白标签挪动
            if (winLeft < 0) {
                var newIndex = 0;
            } else {
                var newIndex = parseInt(winLeft / width) + 1;
            }
            $(li + ".empty").insertBefore(li + ":eq(" + newIndex + ")");
            // console.log(
            //     "startX:" + startX +
            //     ";width:" + width +
            //     ";length:" + length +
            //     ";index:" + index +
            //     ";left:" + left +
            //     ";name:" + name +
            //     ";startX:" + startX +
            //     ";endX:" + endX +
            //     ";moveX:" + moveX +
            //     ";winLeft:" + winLeft +
            //     ";newIndex:" + newIndex
            // );
        }
        //鼠标释放
        document.onmouseout = document.onmouseup = function () {
            //菜单最终位置
            $(thisli).insertBefore(li + ".empty");
            //清理移动效果
            $(li).css({
                "position": "", "top": "", "left": ""
            });
            //清理占位空白标签
            $(li + ".empty").remove();
            //清理事件
            document.onmousemove = null;
            document.onmouseup = null;
            document.onmouseout = null;
        }
    });
}

//把数字金额转换成中文大写数字
function upperMoney(money) {
    var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]; //汉字的数字
    var cnIntRadice = ["", "拾", "佰", "仟"]; //基本单位
    var cnIntUnits = ["", "万", "亿", "兆"]; //对应整数部分扩展单位
    var cnDecUnits = ["角", "分", "毫", "厘"]; //对应小数部分单位
    var cnInteger = "整"; //整数金额时后面跟的字符
    var cnIntLast = "元"; //整型完以后的单位
    var maxNum = 999999999999999.9999; //最大处理的数字
    var IntegerNum; //金额整数部分
    var DecimalNum; //金额小数部分
    var ChineseStr = ""; //输出的中文金额字符串
    var parts; //分离金额后用的数组，预定义
    var Symbol = "";//正负值标记
    var i = 0;
    if (money == "") {
        return "";
    }

    money = parseFloat(money);
    if (money >= maxNum) {
        msg('超出最大处理数字', 'error');
        return "";
    }
    if (money == 0) {
        ChineseStr = cnNums[0] + cnIntLast + cnInteger;
        return ChineseStr;
    }
    if (money < 0) {
        money = -money;
        Symbol = "负 ";
    }
    money = money.toString(); //转换为字符串
    if (money.indexOf(".") == -1) {
        IntegerNum = money;
        DecimalNum = '';
    } else {
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 4);
    }
    if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
        var zeroCount = 0;
        var IntLen = IntegerNum.length;
        for (i; i < IntLen; i++) {
            var n = IntegerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; //归零
                ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                ChineseStr += cnIntUnits[q];
            }
        }
        ChineseStr += cnIntLast;
        //整型部分处理完毕
    }
    if (DecimalNum != '') { //小数部分
        var decLen = DecimalNum.length;
        i = 0;
        for (i; i < decLen; i++) {
            var n = DecimalNum.substr(i, 1);
            if (n != '0') {
                ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (ChineseStr == '') {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (DecimalNum == '') {
        ChineseStr += cnInteger;
    }
    ChineseStr = Symbol + ChineseStr;

    return ChineseStr;
}

/***详情页选项卡切换***/
function detailTab(cla, fun, id) {
    //更新当前页面URL
    $("#renovate").attr("url",getEdit("menu",fun));
    //切换导航
    $("#pageMenu > ul > li").removeClass("pageMenuHover");
    $("[pageMenu=" + fun + "]").addClass("pageMenuHover");
    //切换内容页
    $("[pagediv]").hide();
    if ($("[pagediv=" + fun + "]").length >= 1) {
        $("[pagediv=" + fun + "]").show();
    } else {
        if (cla === 'scheduler') {
            let date = GetQueryString('date');
            if (date) {
                id += '&date=' + date;
            }
        }
        $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun + "&id=" + id, function (data) {
            if (data.warn) {
                warn(data.warn);
            } else if ($("[pagediv=" + fun + "]").length >= 1) { //防止后台推送多次数据
                $("[pagediv=" + fun + "]").html(data.html);
            } else {
                $("#pageMenu").after("<div class='pageDiv' pageDiv='" + fun + "'>" + data.html + "</div>");
            }
        }, "json");
    }
}
/*刷新当前页面*/
function reloadPage(obj){
    window.location.href = $(obj).attr("url");
}
/*修改GET参数*/
function getEdit(key,value){
    //获取当前页面URL
    var oldUrl = document.location.href;
    //获取GET参数
    var one = oldUrl.split("?");
    var get = one[1];
    var para = get.split("&");
    //拼接不需要修改的GET参数
    var newUrl = one[0]+"?";
    for(var i=0;i<para.length;i++){
        if(para[i].indexOf(key+"=") == -1){
            newUrl += para[i]+"&";
        }
    }
    //添加要修改的参数
    newUrl += key+"="+value;
    //返回
    return newUrl;
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/***列表页提交查询按钮***/
function searchFormSub(cla, fun) {
    searchForm(cla, fun, 1);
    return false;
}

/**
 * 列表数据查询函数
 * @param cla 类名
 * @param fun 方法
 * @param page 页码
 * @param formData 是否表单
 * @param option 表头固定参数 fixed 是否表头固定 height 固定高  col 需要固定地列数
 * 不需要表头固定使用 ，请在 searchForm 函数执行完后加入 $('#tableid').fixedThead('destroy')
 */
function searchForm(cla, fun, page, formData = true, option = {fixed: true}) {
    $("#" + fun + "Html").html("数据查询中，请稍后。。。");
    let params = (formData === true) ? $("[name=" + fun + "Form]").serialize() : formData
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun + "&page=" + page, params, function (data) {
        if (data.warn) {
            warn(data.warn);
        } else {
            $("#" + fun + "Html").html(data.html)
            if (fun === 'homeSearch' && option.fixed) {
                // 表格固定
                const obj = $('.tableMany')
                obj.fixedThead.option = option
                obj.fixedThead()
                // 延迟一段时间，等待 fixedThead 创建完成
                setTimeout(function() {
                    // 绑定滚动监听器
                    $('.fixed-thead-body').scroll(function() {
                        // 保存滚动位置
                        var frameSrc = window.frameElement.src; // 获取当前窗口所在的iframe的src属性，确保每个 iframe 使用独立的存储区域
                        var scrollPosition = $(this).scrollTop();
                        if (scrollPosition !== 0) {
                            sessionStorage.setItem('scrollPosition_' + frameSrc, scrollPosition);
                        }
                    });
                }, 100);
            }
        }
        // 加载表格方法
        loadTableTool()
    }, "json");
}

/*表格行点击标记*/
function tableManyClick(obj) {
    $(obj).siblings().removeClass("tableManyClick");
    $(obj).addClass("tableManyClick");
}

/***调取弹出层***/
function layer(cla, fun, json) {
    let con = setTimeout(function () {
        $("#loading", parent.document).hide();
    }, js_configurg.loading_time_out);
    $("#loading", parent.document).show();
    var searchFormId = $(event.target).parents("[searchFormHtml]").attr("searchFormHtml");
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, json, function (data) {
        $("#loading", parent.document).hide();
        clearTimeout(con);
        data.searchFormId = searchFormId;
        layerFun(data);
    }, "json");
}

/***警示弹出层函数***/
function pasWarn(formName, cla, fun) {
    var searchFormId = $(event.target).parent().attr("searchFormHtml");
    $.post(root + 'control/adIndex.html?cla=pasWarn', {
        formName: formName, cla: cla, fun: fun
    }, function (data) {
        data.searchFormId = searchFormId;
        layerFun(data);
    }, 'json');
}

/***弹出层返回函数***/
function layerFun(data) {
    if (data.warn) {
        if (data.warn === 2) {
            if (data.href) {
                window.location.href = data.href;
            } else {
                window.location.reload();
            }
        } else {
            warn(data.warn);
        }
    } else {
        var id = $("#" + data.id);
        if (id.length == 0) {
            var searchFormId = "";
            if (typeof data.searchFormId != "undefined") {
                searchFormId = " searchFormId='" + data.searchFormId + "' ";
            }
            $("#body").append("<div id='" + data.id + "'" + searchFormId + ">" + data.html + "</div>");
        } else {
            id.html(data.html);
            id.css("display", "block");
        }
        move(data.id);
    }
}

/***文件上传函数***/
function icoFun(formName, id) {
    var form = eval('document.' + formName);
    form.id.value = id;
    form.file.click();
}

/***项目管理-我的任务-项目网页-以文件形式更新网页***/
function projectPageUpdate(projectPageId) {
    var form = document.pageUpdateForm;
    form.projectPageId.value = projectPageId;
    form.file.click();
}

/***生成密码***/
function getPas() {
    var num = "";
    for (var i = 0; i < 6; i++) {
        num += Math.floor(Math.random() * 10);
    }
    document.staffForm.password.value = num;
}

/***主页-修改密码-发送手机短信验证码***/
function pasSms() {
    $.post(root + "control/adIndex.html?cla=my&fun=pasSms", function (data) {
        warn(data.warn);
    }, "json");
}

/***忘记密码-根据登录用户名发送手机短信验证码-登录时使用***/
function pas(name) {
    $.post(root + "library/libData.html?type=adForgetPassword", {
        name: name
    }, function (data) {
        warn(data.warn);
    }, "json");
}

/***全选***/
function checkAll(obj) {
    var formName = $(obj).attr("form");
    var checkName = $(obj).attr("name");
    var bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    console.log(bool)
    $("[name='" + formName + "'] [name='" + checkName + "\[\]'").prop('checked', bool);
}

/*全选本区域权限*/
function powerCheckAll(obj) {
    var bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    $(obj).parents(".box").find(":checkbox").prop('checked', bool);
}

//php的checkbox函数自带js
function checkboxAll(obj) {
    var name = $(obj).val();
    let bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    $(obj).parent().siblings("label").children("[name='" + name + "\[\]']").prop('checked', bool);
}


/*将下拉菜单赋值到下一个输入框*/
function selectGetText(obj) {
    $(obj).next().val(obj.value);
}

/***人力资源管理 - 行政人事 - 职位管理 根据一级导航查询二级导航***/
function getPowerTwo(obj, name = 'powerTwo', value = '') {
    var val = obj.value;
    $.post(root + "control/adIndex.html?cla=role&fun=getPowerName", {
        name: val, value: value
    }, function (data) {
        $(obj).siblings('[name="' + name + '"]').html(data.res);
    }, "json");
}

function getPowerThree(obj, name = 'powerThree', oneName = 'powerOne', field = 'name', value = '') {
    var val = obj.value, one = $(obj).siblings('[name="' + oneName + '"]').val();
    $.post(root + "control/adIndex.html?cla=role&fun=getPowerName", {
        name: one + '-' + val, level: 3, field: field, value: value
    }, function (data) {
        $(obj).siblings('[name="' + name + '"]').html(data.res);
    }, "json");
}

/*行政人事-根据分类加载部门*/
function getDeparment(obj) {
    $.post(root + "control/adIndex.html?cla=staff&fun=getDeparment", {
        type: obj.value
    }, function (data) {
        //本分类下部门选项
        var departmentId = $(obj).next("select");
        if (departmentId.attr("title") == "当前部门") {
            departmentId.html(data.departmentId);
        }
        //本部门下职位
        var jobId = $(obj).nextAll("select").eq(1);
        if (jobId.attr("title") == "当前职位") {
            jobId.html("<option value=''>-当前职位-</option>");
        }
        //本职位下员工
        var staffId = $(obj).nextAll("select").eq(2);
        if (staffId.attr("title") == "员工") {
            staffId.html("<option value=''>-员工-</option>");
        }

    }, "json");
}

/*行政人事-根据部门ID加载职位*/
function getJob(obj) {
    $.post(root + "control/adIndex.html?cla=staff&fun=getJob", {
        deparmentId: obj.value
    }, function (data) {
        //本部门下职位
        var jobId = $(obj).next("select[name='jobId']");
        jobId.html(data.jobId);
        //本职位下员工
        var staffId = $(obj).nextAll("select").eq(1);
        staffId.html("<option value=''>-员工-</option>");

    }, "json");
}

/*行政人事-根据职位ID加载员工*/
function getStaff(obj) {
    $.post(root + "control/adIndex.html?cla=staff&fun=getStaff", {
        jobId: obj.value
    }, function (data) {
        var stid = $(obj).next("select");
        stid.html(data.stid);
    }, "json");
}

/***行政人事-员工管理-社保扣款-汇总员工结算账户***/
function lastMoneyCutAll() {
    var moneyAll = 0;
    $("[name=lastMoneyCutForm] [name=lastMoneyCut]").each(function () {
        var money = parseFloat($(this).val());
        moneyAll += money;
    });
    $("#lastMoneyCutAllId").text("￥" + moneyAll.toFixed(2));
}

/***行政人事-员工管理-社保扣款-提交***/
function lastMoneyCutFormSub() {
    //获取员工和扣款关联数组
    var lastMoneyCut = {};
    $("[name=lastMoneyCutForm] [name=lastMoneyCut]").each(function () {
        var key = $(this).attr("stid");
        lastMoneyCut[key] = $(this).val();
    });
    //整理json数组
    var postData = {
        "lastMoneyCut": lastMoneyCut
    };
    //提交
    $.post(root + "control/adIndex.html?cla=settlementAccounts&fun=lastMoneyCutFormSub", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

/*员工选择器-搜索员工*/
function staffChoice(obj) {
    var quit = "no";
    if ($("#staffQuit").hasClass("staffQuitChoice")) {
        quit = "yes";
    }
    staffSearch({
        name: $(obj).val(), quit: quit
    });
}

/*员工选择器-初始化*/
function staffChoiceClear() {
    $("#staffChoiceSearch").val("");
    staffSearch({
        name: ""
    });
}

/*员工选择器-根据职位查询员工*/
function staffChoiceDepartment(departmentId) {
    staffSearch({
        departmentId: departmentId
    });
}

/*员工选择器-显示离职员工*/
function staffQuit(obj) {
    //切换离职按钮效果
    $(obj).toggleClass("staffQuitChoice");
    //如果查询框有值，则重新查询
    var staffChoiceSearch = $("#staffChoiceSearch").val();
    if (staffChoiceSearch != "") {
        if ($("#staffQuit").hasClass("staffQuitChoice")) {
            var quit = "yes";
        } else {
            var quit = "no";
        }
        staffSearch({
            name: staffChoiceSearch, quit: quit
        });
    }
}

/*员工选择器-异步获取员工列表*/
function staffSearch(json) {
    $.post(root + "control/adIndex.html?cla=examine&fun=staffChoiceSearch", json, function (data) {
        $("#staffChoiceResult").html(data.html);
    }, "json");
}

/*员工选择器-选择员工*/
function staffClick(stid, name, src) {
    if ($("[examineStaff='" + stid + "']").length > 0) {
        warn("此审批人已经存在");
    } else {
        $('#examineStaffChoice').hide();
        $("#staffAdd").before("<div examineStaff='" + stid + "'><img src='" + src + "'><div onclick='staffChoiceDel(this)'>×</div><div>" + name + "</div><img src='" + root + "img/images/link.png'></div>");
    }
}

function staffChoiceDel(obj) {
    $(obj).parent().remove();
}

/*行政人事-工作事务-编辑页面-提交*/
function examineSub() {
    //获取审核人
    var staffId = new [];
    $("[examineStaff]").each(function () {
        staffId.push($(this).attr("examineStaff"));
    });
    //整理json数组
    var postData = {
        "target": document.examineDetail.target.value,
        "jobId": document.examineDetail.jobId.value,
        "list": document.examineDetail.list.value,
        "text": document.examineDetail.text.value,
        "id": document.examineDetail.id.value,
        "staffId": staffId,
    };
    //提交
    $.post(root + "control/adIndex.html?cla=examine&fun=examineSub", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

/***行政人事-工作日-选择工作日***/
function squareLiChoice(obj) {
    var squareLi = $(obj).attr("squareLi");
    if (squareLi == "no") {
        $(obj).attr("squareLi", "yes");
    } else if (squareLi == "yes") {
        $(obj).attr("squareLi", "no");
    }
}

/***行政人事-工作日-提交工作日***/
function workDaySub(obj) {
    var workDay = new [];
    $("[squareLi=yes]").each(function () {
        workDay.push($(this).attr("workDayLiNum"));
    });
    var postData = {
        "moon": document.detailForm.moon.value,
        "text": document.detailForm.text.value,
        "id": document.detailForm.id.value,
        "workDay": workDay
    };
    $.post(root + "control/adIndex.html?cla=workDay&fun=detailEdit", postData, function (data) {
        if (data.warn == 2) {
            window.location.href = data.href;
        } else {
            warn(data.warn);
        }
    }, "json");
}

/*行政人事-提交加班成果报告-根据关键词获取加班对象*/
function workAddFruitShow(obj) {
    $(obj).siblings(".asynchronousMenu").show();
    workAddFruitKey(obj);
}

function workAddFruitKey(obj) {
    var target = document.workAddFruitForm.target.value; //加班对象
    var key = document.workAddFruitForm.targetId.value; //关键词
    $.post(root + "control/adIndex.html?cla=workAdd&fun=fruitKey", {
        target: target, key: key
    }, function (data) {
        $(obj).siblings(".asynchronousMenu").children("ul").html(data.html);
    }, "json");
}

function workAddFruitName(obj) {
    var name = $(obj).html();
    var targetId = $(obj).attr("fruitTargetId");
    var input = $(obj).parents(".asynchronousMenu").siblings("[name=targetId]");
    input.val(name);
    input.attr("targetId", targetId);
}

function workAddFruitHide(obj) {
    $(obj).siblings(".asynchronousMenu").hide();
}

/*行政人事-提交加班成果报告-添加加班成果*/
function workAddFruitSub() {
    //组合tr
    var form = document.workAddFruitForm;
    var target = form.target.value;
    var targetId = form.targetId.getAttribute("targetId");
    var targetName = $("[fruitTargetId='" + targetId + "']").text();
    var hour = form.hour.value;
    var text = form.text.value;
    var fruitId = form.fruitId.value;
    var button = "<span fruitId='" + fruitId + "' target='" + target + "' targetId='" + targetId + "' hour='" + hour + "' text='" + text + "' onclick=\"workAddFruitEdit(this)\" class='spanButton'>编辑</span>" + "\n<span onclick=\"workAddFruitDel(this)\" class='spanButton'>删除</span>";
    var checkTarget = $("#workAddFruitTable").find("[targetId='" + targetId + "']");
    var checkTr = $("#workAddFruitTable").find("[fruitId='" + fruitId + "']");
    var checkPrice = /^[0-9]+(.[0-9]{1,2})?$/;
    if (target == "") {
        warn("请选择加班对象");
    } else if (form.targetId.value == "") {
        warn("请选择对象名称");
    } else if (targetName == "") {
        warn("未找到此对象名称");
    } else if (hour == "") {
        warn("请输入加班小时数");
    } else if (!checkPrice.test(hour)) {
        warn("加班小时数格式有误");
    } else if (text == "") {
        warn("请填写加班成果");
    } else if (checkTarget.length > 0 && checkTarget.attr("fruitId") != fruitId) {
        warn("此加班对象已存在");
    } else {
        //如果此记录已存在，则先删除
        if (checkTr.length > 0) {
            checkTr.parents("tr").remove();
        }
        //插入tr
        var dataTr = "<tr><td>" + button + "</td><td>" + target + "</td><td><div>" + targetName + "</div></td><td>" + hour + "</td><td><div>" + text + "</div></td></tr>";
        var tr = $("#workAddFruitTable tr").eq(0);
        tr.after(dataTr);
        //清理提示
        if (tr.text() == "一条记录都没有") {
            tr.remove();
        }
        //关闭弹出层
        $("#workAddFruit").hide();
    }
}

/*行政人事-提交加班成果报告-编辑加班成果*/
function workAddFruitEdit(obj) {
    var form = document.workAddFruitForm;
    var postData = {
        "target": $(obj).attr("target"),
        "targetId": $(obj).attr("targetId"),
        "targetName": $(obj).parents("tr").children().eq(2).text(),
        "hour": $(obj).attr("hour"),
        "text": $(obj).attr("text"),
        "fruitId": $(obj).attr("fruitId")
    };
    layer('workAdd', 'fruit', postData);
}

/*行政人事-提交加班成果报告-删除加班成果*/
function workAddFruitDel(obj) {
    $(obj).parents("tr").remove();
}

function workAddSub() {
    //加班成果列表
    var fruit = {};
    $("[fruitId]").each(function () {
        var id = $(this).attr("fruitId");
        fruit[id] = {
            "target": $(this).attr("target"),
            "targetId": $(this).attr("targetId"),
            "hour": $(this).attr("hour"),
            "text": $(this).attr("text")
        }
    });
    //整理json数组
    var form = document.workAddTimeForm;
    var postData = {
        "fruit": fruit, "timeStart": form.timeStart.value, "timeEnd": form.timeEnd.value, "id": form.id.value
    };
    //请求服务器
    $.post(root + "control/adIndex.html?cla=workAdd&fun=resultEdit", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

/*行政人事-提交外出成果报告-根据关键词获取外出对象*/
function workOutFruitShow(obj) {
    $(obj).siblings(".asynchronousMenu").show();
    workOutFruitKey(obj);
}

function workOutFruitKey(obj) {
    var target = document.workOutFruitForm.target.value; //外出对象
    var key = document.workOutFruitForm.targetId.value; //关键词
    $.post(root + "control/adIndex.html?cla=workOut&fun=fruitKey", {
        target: target, key: key
    }, function (data) {
        $(obj).siblings(".asynchronousMenu").children("ul").html(data.html);
    }, "json");
}

function workOutFruitName(obj) {
    var name = $(obj).html();
    var targetId = $(obj).attr("fruitTargetId");
    var input = $(obj).parents(".asynchronousMenu").siblings("[name=targetId]");
    input.val(name);
    input.attr("targetId", targetId);
}

function workOutFruitHide(obj) {
    $(obj).siblings(".asynchronousMenu").hide();
}

/*行政人事-提交外出成果报告-添加外出成果*/
function workOutFruitSub() {
    //组合tr
    var form = document.workOutFruitForm;
    var target = form.target.value;
    var targetId = form.targetId.getAttribute("targetId");
    var targetName = $("[fruitTargetId='" + targetId + "']").text();
    var hour = form.hour.value;
    var text = form.text.value;
    var fruitId = form.fruitId.value;
    var button = "<span fruitId='" + fruitId + "' target='" + target + "' targetId='" + targetId + "' hour='" + hour + "' text='" + text + "' onclick=\"workOutFruitEdit(this)\" class='spanButton'>编辑</span>" + "\n<span onclick=\"workOutFruitDel(this)\" class='spanButton'>删除</span>";
    var checkTarget = $("#workOutFruitTable").find("[targetId='" + targetId + "']");
    var checkTr = $("#workOutFruitTable").find("[fruitId='" + fruitId + "']");
    var checkPrice = /^[0-9]+(.[0-9]{1,2})?$/;
    if (target == "") {
        warn("请选择外出对象");
    } else if (form.targetId.value == "") {
        warn("请选择对象名称");
    } else if (targetName == "") {
        warn("未找到此对象名称");
    } else if (hour == "") {
        warn("请输入外出小时数");
    } else if (!checkPrice.test(hour)) {
        warn("外出小时数格式有误");
    } else if (text == "") {
        warn("请填写外出成果");
    } else if (checkTarget.length > 0 && checkTarget.attr("fruitId") != fruitId) {
        warn("此外出对象已存在");
    } else {
        //如果此记录已存在，则先删除
        if (checkTr.length > 0) {
            checkTr.parents("tr").remove();
        }
        //插入tr
        var dataTr = "<tr><td>" + button + "</td><td>" + target + "</td><td><div>" + targetName + "</div></td><td>" + hour + "</td><td><div>" + text + "</div></td></tr>";
        var tr = $("#workOutFruitTable tr").eq(0);
        tr.after(dataTr);
        //清理提示
        if (tr.text() == "一条记录都没有") {
            tr.remove();
        }
        //关闭弹出层
        $("#workOutFruit").hide();
    }
}

/*行政人事-提交外出成果报告-编辑外出成果*/
function workOutFruitEdit(obj) {
    var form = document.workOutFruitForm;
    var postData = {
        "target": $(obj).attr("target"),
        "targetId": $(obj).attr("targetId"),
        "targetName": $(obj).parents("tr").children().eq(2).text(),
        "hour": $(obj).attr("hour"),
        "text": $(obj).attr("text"),
        "fruitId": $(obj).attr("fruitId")
    };
    layer('workOut', 'fruit', postData);
}

/*行政人事-提交外出成果报告-删除外出成果*/
function workOutFruitDel(obj) {
    $(obj).parents("tr").remove();
}

/***行政人事-外出申请-提交现场照片***/
function workOutIco() {
    document.workOutIcoForm.file.click();
}

function workOutChange() {
    $("#workOutImg").attr("src", getFileUrl("workOutIcoFile"));
}

function workOutSub() {
    //外出成果列表
    var fruit = {};
    $("[fruitId]").each(function () {
        var id = $(this).attr("fruitId");
        fruit[id] = {
            "target": $(this).attr("target"),
            "targetId": $(this).attr("targetId"),
            "hour": $(this).attr("hour"),
            "text": $(this).attr("text")
        }
    });
    //整理json数组
    var form = document.workOutTimeForm;
    var postData = {
        "fruit": fruit, "timeStart": form.timeStart.value, "timeEnd": form.timeEnd.value, "id": form.id.value
    };
    //请求服务器
    $.post(root + "control/adIndex.html?cla=workOut&fun=resultEdit", postData, function (data) {
        if (data.warn == 2) {
            var ico = document.workOutIcoForm.file.value;
            if (!!ico) {
                document.workOutIcoForm.submit();
            } else {
                window.location.reload();
            }
        } else {
            warn(data.warn);
        }
    }, "json");
}

/***财务会计-收支平衡-根据方向选择类型***/
function profitDirectionToType(obj) {
    $.post(root + "control/adIndex.html?cla=profit&fun=profitGetType", {
        direction: $(obj).val()
    }, function (data) {
        $(obj).siblings("[name=type]").html(data.type);
    }, "json");
}

/***代理日志-查询二级菜单***/
function getAgMenuTwo(obj) {
    $.post(root + "control/adIndex.html?cla=agLog&fun=getAgMenuTwo", {
        menuOne: $(obj).val()
    }, function (data) {
        $(obj).siblings("[name=menuTwo]").html(data.menuTwo);
    }, "json");
}

/***客户管理-客户列表-公私客转换***/
function publicClient(obj, khid) {
    $.post(root + "control/adIndex.html?cla=client&fun=publicClient", {
        khid: khid
    }, function (data) {
        if (data.warn == "更新成功") {
            $(obj).html(data.text);
            $("#nowAdName").html(data.name);
        }
        warn(data.warn);
    }, "json");
}


//展示输入框
function showInput(e) {
    $.post(root + 'control/adIndex.html?cla=component&fun=showInput', {}, function (res) {
        $(e).parent().before(res.html);
        $(e).css('display', 'none');
    }, 'json')
}

//展示添加按钮
function showAddButton(e) {
    let val = e.value;
    $.post(root + 'control/adIndex.html?cla=component&fun=showAddButton', {val: val}, function (res) {
        $(e).parent().after(res.html);
        $(e).parent().remove();
        $(".add-attr-button").css('display', 'inline-flex');
    }, 'json')
}

/***客户管理-客户列表-开票记录-更新发票扫描件***/
function clientInvoiceIcoFun(id) {
    var form = document.clientInvoiceIcoForm;
    form.clientInvoiceId.value = id;
    form.file.click();
}


/***标签删除**/
function del_this(e) {
    $(e).parent().remove();
}

/*附件-切换保密状态*/
function fileSecret(obj) {
    $.post(root + "control/adIndex.html?cla=file&fun=fileSecret", {
        id: $(obj).attr("id")
    }, function (data) {
        if (data.warn) {
            warn(data.warn);
        } else {
            $(obj).html(data.secret);
            $(obj).attr("title", data.title);
        }
    }, "json");
}

/***下载量***/
function downloadNum(name, id) {
    $.post(root + "control/data?type=" + name, {
        id: id
    });
}

/***系统设置-文章管理-根据一级分类返回二级分类***/
function getContentClassify(obj) {
    var type = obj.value;
    $.post(root + "control/adIndex.html?cla=content&fun=getContentClassify", {
        type: type
    }, function (data) {
        $(obj).siblings("[name=classify]").html(data.classify);
    }, "json");
}

/***系统设置-文章管理-将一级分类赋予输入框，返回二级分类，清理二级分类输入框***/
function giveContentType(obj) {
    var form = document.detailForm;
    form.type.value = obj.value;
    form.classify.value = "";
    $.post(root + "control/adIndex.html?cla=content&fun=getContentClassify", {
        type: obj.value
    }, function (data) {
        form.classifySelect.innerHTML = data.classify;
    }, "json");
}

/***系统设置-文章管理-将二级分类录入输入框***/
function giveContentClassify(obj) {
    document.detailForm.classify.value = obj.value;
}

// ul 缩放
function ulScal(obj, id) {
    let has = $(obj).nextAll('[pid="' + id + '"]')
    if (has.length > 0) {
        if (has.is(":hidden")) {
            $(obj).find('.arrow').css({
                'transform': 'rotate(180deg)',
            })
            has.show()
        } else {
            $(obj).find('.arrow').css({
                'transform': 'rotate(90deg)',
            })
            has.hide()
        }
    }

}

// 部门详情
function departmentDetail(obj, cla = 'department') {
    let id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
        $("#container-left li").removeClass('active');
        $(obj).addClass('active')
        $.post(root + "control/adIndex.html?cla=" + cla + "&fun=detail", {
            id: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}

// 文档中心自动加载选中
function documentCenterChoice(id) {
    let obj = $("[data-id='" + id + "']")
    if (obj.length > 0) {
        ulScal(obj, id)
        $(obj).addClass('active')
        $.post(root + "control/adIndex.html?cla=documentCenter&fun=detail", {
            id: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}


function replaceDetail(obj, cla) {
    return departmentDetail(obj, cla)
}

// 职位
function replaceRight(obj, cla = 'job') {
    let api, id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
        $(obj).addClass('active')
        api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson'
        $.post(api, {
            objId: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}

/**
 * 树形缩放
 * @param obj
 */
function liZoom(obj) {
    let id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
    }
    window.event.stopPropagation();//阻止事件冒泡
}

/**
 * 获取右边内容
 * @param obj
 * @param cla
 */
function replaceContent(obj, cla) {
    let id = $(obj).attr('data-id');
    let api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson';
    if (id.length > 0) {
        $("#container-left li").removeClass('active');
        $(obj).addClass('active')
        $.post(api, {
            objId: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}


function containerLeftSearch(obj, type = 'department') {
    // 业务函数
    let keyword = obj.value.trim()
    let box = $('#container-left').find('ul[pid="0"]')
    $.post(root + 'control/adIndex.html?cla=' + type + '&fun=getContainerLeftJson', {
        type: type
    }, function (data) {
        if (keyword.length > 0) {
            //过滤掉data-id 是汉字的情况
            let hightlightText = (data.html).replace(new RegExp(`(?<!id=')(${keyword})`, 'g'), `<em class="keyword-match">$1</em>`);
            box.html(hightlightText)
        } else {
            box.html(data.html)
        }
    }, "json");
}

/**
 * 分类树形导航搜索
 */
function search_left(){
    let arg = arguments
    let keyword = arg[0].value
    //回车查询，关键词一样，则一直往下定位
    if(arg[1] !== undefined && arg[1].keyCode === 13){
        findNextMatch();
    }else{
        findMatches(keyword, '.container-left li > .textcontent')
    }
}

/**
 * 已匹配关键字，回车查找下一个
 */
function findNextMatch() {
    let allMatch = document.querySelectorAll('.keyword-match')
    if (allMatch.length > 0) {
        // 获取所有的keyword-match节点
        const keywordMatches = Array.from(allMatch);
        // 查找now-keyword-match在数组中的位置
        const nowKeywordMatchIndex = keywordMatches.indexOf(document.querySelector('.now-keyword-match'));

        allMatch[nowKeywordMatchIndex].classList.remove('now-keyword-match');
        // 查找下一个匹配项
        let nextMatch = nowKeywordMatchIndex*1+1;  // 下一个匹配项
        if (allMatch[nextMatch] === undefined) {
            nextMatch = 0
        }
        allMatch[nextMatch].scrollIntoView({behavior: "smooth", block: "center", inline: "center"});
        allMatch[nextMatch].classList.add('now-keyword-match');
    }
}
/**
 * 分类树形导航搜索，匹配所有关键字
 * @param keyword 关键字
 * @param querySelectorAll 搜索节点，例如：.container-left li > .textcontent
 * @returns {[]}
 */
function findMatches(keyword, querySelectorAll, scrollingArea = '.classify-area') {
    let matches = [];
    //找到所有节点
    let elements = document.querySelectorAll(querySelectorAll);
    //先清空前面搜索的标识
    for (let i = 0; i < elements.length; i++) {
        let element = elements[i];
        let htmlContent = element.innerHTML;
        let plainText = htmlContent.replace(/<em class="keyword-match( now-keyword-match)?">|<\/em>/g, '');
        element.innerHTML = plainText;
    }
    if (keyword) {
        keyword = keyword.trim();
        for (let i = 0; i < elements.length; i++) {
            let element = elements[i];
            let textContent = element.textContent;
            let regex = new RegExp(keyword, 'gi');
            if (textContent.indexOf(keyword) >= 0) {
                //关键词高亮显示
                let highlightedText = textContent.replace(regex, `<em class="keyword-match">$&</em>`);
                element.innerHTML = highlightedText;
                matches.push(element);
            }
        }
        //定位到第一个关键字出现的位置
        if (matches.length > 0) {
            matches[0].scrollIntoView({behavior: "smooth", block: "center", inline: "center"}); // 滚动到第一个匹配结果
            matches[0].querySelector('.keyword-match').classList.add('now-keyword-match');
        }
    }else{
        document.querySelector(scrollingArea).scrollTop = 0
    }
    return matches;
}
/**
 * 保存分类搜索session
 * @param obj
 * @param cla
 * @param page
 */
function typeSession(obj, cla, page) {
    // 业务函数
    let keyword = obj.value
    $.post(root + 'control/adIndex.html?cla='+cla+'&fun=typeSession', {
        page: page,
        keyword: keyword
    }, function (data) {
    }, "json");
}

// ul选择后赋值到指定ele函数
function selection(obj, ele) {
    let id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
        $(obj).addClass('active')
        $('#' + ele).val(id)
    }
}

// 单个文本框更新
function textUpdate(obj, cla, fun) {
    let field = $(obj).attr('name'), val = $(obj).val()
    if (field.length > 0 && val.length > 0) {
        const url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun
        let params = {}
        // 判断是否有data-* 参数
        if ($(obj).data()) {
            Object.assign(params, $(obj).data())
            params[field] = val
        }
        $.post(url, params, function (resp) {
            if (resp.warn == 2) {
                if (resp.href) {
                    window.location.href = resp.href;
                } else {
                    window.location.reload();
                }
            } else {
                warn(resp.warn)
            }
        }, "json");
    }
}

/**
 * 删除行
 * @param e
 */
function decline(e) {
    $(e).parent().parent().remove();
}

function decRow(e) {
    $(e).parent().remove();
}

/**随机字符串**/
function randomString(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    let i = 0;
    for (i; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function button_method(e, power = '') {
    let type = $(e).data('type');
    if (type === 'add') {
        $('#uploadFile').click();
    } else if (type === 'delete') {
        let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
        let id = $("[name='fileId']").val();
        $.post(url, {
            id: id, power: power
        }, function (res) {
            if (res.warn === 2) {
                $("#singFileName").html('');
                $("#upload-ico").attr('src', root + "img/control/upload.svg");
                $("[name='fileId']").val('');
                $("#upload-ico").data('type', 'add');
            } else {
                warn(res.warn);
            }
        }, 'json')
    }
}

/**
 * 单文件上传
 */
function uploadSingleFile(formName, url) {
    //等待动画
    let con = setTimeout(function () {
        $("#loading", parent.document).hide();
    }, js_configurg.loading_time_out)
    $("#loading", parent.document).show();
    let form = $("form[name='" + formName + "']")[0];
    let formData = new FormData(form);
    $.ajax({
        type: "POST",
        contentType: false,
        processData: false,
        url: url,
        data: formData,
        cache: false,
        success: function (res) {
            let result = JSON.parse(res);
            if (result.warn === 2) {
                $("[name='fileId']").val(result.data.id);
                $("#upload-ico").attr('src', root + "img/control/delete.svg");
                $("#singFileName").html(result.data.name);
                $("#upload-ico").data('type', 'delete');
            } else {
                warn(result.warn)
            }
        },
        error: function (e) {
            console.log(e)
            warn("上传失败");
        },
        complete: function () {
            $("[name='uploadFile']").val('');
            $("#loading", parent.document).hide();
            clearTimeout(con);
        }
    });
}

//上传附件
function uploadAttachFile(formName, url, htmlId) {
    //等待动画
    let con = setTimeout(function () {
        $("#loading", parent.document).hide();
    }, js_configurg.loading_time_out)
    $("#loading", parent.document).show();
    let form = $("form[name='" + formName + "']")[0];
    let formData = new FormData(form);
    $.ajax({
        type: "POST",
        contentType: false,
        processData: false,
        url: url,
        data: formData,
        cache: false,
        success: function (res) {
            let result = JSON.parse(res);
            if (result.warn === 2) {
                $("[name='" + formName + "'] #" + htmlId + "").before(result.data.html);
            } else {
                warn(result.warn)
            }
        },
        error: function (e) {
            console.log(e)
            warn("上传失败");
        },
        complete: function () {
            $("[name='" + formName + "'] [name='uploadFile']").val('');
            $("#loading", parent.document).hide();
            clearTimeout(con);
        }
    });
}

function allowDrop(ev) {
    ev.preventDefault();
}

function pasteFile(event, formName, url, htmlId, type = 'paste') {
    //等待动画
    let con = setTimeout(function () {
        $("#loading", parent.document).hide();
    }, js_configurg.loading_time_out)
    $("#loading", parent.document).show();
    var e = event || window.event;
    e.preventDefault()
    e.stopPropagation()
    if (type === 'drop') {
        var files = e.dataTransfer.files;//获取拖拽的文件

    } else {
        var files = e.clipboardData.files;//获取剪贴徳的图片信息
    }
    $.each(files, function (n, file) {
        let form = $("form[name='" + formName + "']")[0];
        let formData = new FormData(form);
        formData.append("uploadFile", file);
        $.ajax({
            type: "POST",
            contentType: false,
            processData: false,
            url: url,
            data: formData,
            cache: false,
            success: function (res) {
                let result = JSON.parse(res);
                if (result.warn === 2) {
                    $("[name='" + formName + "'] #" + htmlId + "").before(result.data.html);
                } else {
                    warn(result.warn)
                }
            },
            error: function (e) {
                console.log(e)
                warn("上传失败");
            },
            complete: function () {
                $("[name='" + formName + "'] [name='uploadFile']").val('');
                $("#loading", parent.document).hide();
                clearTimeout(con);
            }
        });
    });


}

//删除附件
function delFile(id, cla, e) {
    let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
    $.post(url, {
        id: id, power: cla
    }, function (res) {
        if (res.warn === 2) {
            $(e).parent().parent().remove();
        } else {
            warn(res.warn);
        }
    }, 'json')
}


function showState(event) {
    let state = $(".stateBlock").css('display');
    if (state == 'block') {
        $(".stateBlock").hide();
    } else {
        $(".stateBlock").show();
    }
}

/**
 * 仅周一
 */
function onlyMonday() {
    $(".layui-laydate-content table tr td:nth-child(1)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(3)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(4)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(5)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(6)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(7)").addClass('laydate-disabled')
}

/** 页面打印 */
function printPage(cla, fun = 'printPage', formName = 'listForm') {
    let body = '', data = $('[name="' + formName + '"]').serializeArray()
    data.forEach(ele => {
        body += ele.value + ';'
    });
    if (body.length > 0) {
        let url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun + '&body=' + body
        window.open(url)
    } else {
        warn('请选择你要打印的条目')
        return false
    }
}

/******获取表中选中的数据*******/
function get_checked_box(cla, fun, formName) {
    let arr = [];
    $("[name='" + formName + "'] input:checkbox[name='listId[]']:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
        layer(cla, fun, {listId: vals});
    } else {
        msg('请选择需要数据');
    }
}
function get_checked_box1(cla, fun, formName,type=1) {
    let arr = [];
    $("[name='" + formName + "'] input:checkbox[name='listId[]']:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
        // layer(cla, fun, {listId: vals,type:type});
        var url=root + "control/adIndex.html?cla=" + cla + "&fun=" + fun+"&listId="+vals+"&type="+type

        window.open(url)
    } else {
        msg('请选择需要数据');
    }
}
function get_checked_box_val(formName) {
    let arr = [];
    $("[name='" + formName + "'] input:checkbox[name='listId[]']:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
        console.log('vals',vals)
       return vals;
    } else {
        // msg('请选择需要数据');
        return '';
    }
}
// 复制
function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name=" + name + "]").val(val);
}

/**
 * 员工选择器-删除
 */
function del_staff(e) {
    let id = $(e).data('stid')
    let boxid = $(e).data('boxid'),
        hidden = $("#" + boxid + " #" + boxid + "layer")
    //$("#staff-box [name='staff[]']")
    id += ';';
    let stid = hidden.val();
    stid = stid.replace(id, '');
    hidden.val(stid);
    $(e).prev().remove();
    $(e).remove();
}

/**操作url参数****/
var urlHelper = {
    /****获取参数***/
    getUrlParam: function (url, ref) {
        let str = "";
        // 如果不包括此参数
        if (url.indexOf(ref) == -1) {
            return "";
        }
        str = url.substr(url.indexOf('?') + 1);
        let arr = str.split('&');
        let i = '';
        for (i in arr) {
            let paired = arr[i].split('=');
            if (paired[0] == ref) {
                return paired[1];
            }
        }
        return "";
    }, /****增加参数***/
    addUrlParam: function (url, ref, value) {
        // 如果没有参数
        if (url.indexOf('?') == -1) {
            return url + "?" + ref + "=" + value;
        }
        // 如果不包括此参数
        if (url.indexOf(ref) == -1) {
            return url + "&" + ref + "=" + value;
        }
        var arr_url = url.split('?');
        var base = arr_url[0];
        var arr_param = arr_url[1].split('&');
        let i = 0;
        for (i; i < arr_param.length; i++) {
            let paired = arr_param[i].split('=');
            if (paired[0] == ref) {
                paired[1] = value;
                arr_param[i] = paired.join('=');
                break;
            }
        }

        return base + "?" + arr_param.join('&');
    }, /****删除参数***/
    delUrlParam: function (url, ref) {
        // 如果不包括此参数
        if (url.indexOf(ref) == -1) {
            return url;
        }
        var arr_url = url.split('?');
        var base = arr_url[0];
        var arr_param = arr_url[1].split('&');
        var index = -1;
        let i = 0;
        for (i; i < arr_param.length; i++) {
            var paired = arr_param[i].split('=');
            if (paired[0] == ref) {
                index = i;
                break;
            }
        }

        if (index == -1) {
            return url;
        } else {
            arr_param.splice(index, 1);
            return base + "?" + arr_param.join('&');
        }
    }
};

/***详情页选项卡切换***/
function liTab(cla, fun, id) {
    //切换导航
    $("#liMenu > ul > li").removeClass("pageMenuHover");
    $("[liMenu=" + fun + "]").addClass("pageMenuHover");
    //切换内容页
    $("[page_content]").hide();
    if ($("[page_content=" + fun + "]").length >= 1) {
        $("[page_content=" + fun + "]").show();
    } else {
        $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun + "&id=" + id, function (data) {
            if (data.warn) {
                warn(data.warn);
            } else if ($("[page_content=" + fun + "]").length >= 1) { //防止后台推送多次数据
                $("[page_content=" + fun + "]").html(data.html);
            } else {
                $("#liMenu").after("<div class='pageDiv' page_content='" + fun + "'>" + data.html + "</div>");
            }
        }, "json");
    }
}

$("#record").mouseover(function () {
    showState();
});
$("#record").mouseout(function () {
    showState();
});
//点击非下拉区域隐藏
$(document, window.parent.document).bind('click', function (e) {
    let target = $("#searchMenu", window.parent.document);
    if (!target.is(e.target) && target.has(e.target).length === 0) {
        $("#searchMenuText", window.parent.document).hide();
        $("#bigAutocompleteContent", window.parent.document).hide();
    }
    target = $("#user", window.parent.document);
    if (!target.is(e.target) && target.has(e.target).length === 0) {
        $(".userList", window.parent.document).hide();
    }
});

//默认结算周期
function settlementDayDefault(e) {
    let type = e.value;
    let days = $(e).parents('li').find("[name='settlementDay']").val()
    if (type === '月结' && days === '') {
        $("[name='settlementDay']").val('30')
    }
}

//对输入金额进行校验
function digitalFiltering(obj, num) {
    obj.value = obj.value.replace(/[^\d.]/g, "");//清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, "");//验证第一个字符是数字而不是字符
    obj.value = obj.value.replace(/\.{2,}/g, ".");//只保留第一个.清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(new RegExp(`^(\\-)*(\\d+)\\.(\\d{${num}}).*$`), '$1$2.$3');//只能输入两个小数
}


/**
 * 科目选择器--弹窗
 * @param e
 * @param name
 * @param isShow
 */
function chooseSubject(e, name, isShow) {
    let rowId = $("[name='" + name + "']").attr('id');
    layer('component', 'subject', {isShow: isShow, rowId: rowId})
}

/**
 *科目选择器--弹窗点击科目事件
 * @param e
 */
function chooseSubjectId(e) {
    let id = $(e).data('id');
    let name = $(e).data('name');
    $(e).parent().find("li").css('background-color', 'white');
    $(e).css('background-color', "rgb(242, 242, 242)");
    $("[name='chooseId']").val(id);
    $("[name='chooseName']").val(name);
}

/**
 * 科目选择器--弹窗确认按钮事件
 * @param selectorId
 * @returns {boolean}
 */
function confirmBtn(selectorId) {
    let id = $("[name='chooseId']").val();
    let name = $("[name='chooseName']").val();
    if (!id) {
        msg('请选择科目', 'error')
        return false;
    }
    let hiddenName = $("#" + selectorId).data('name');
    $("#" + selectorId).siblings("input[name='" + hiddenName + "']").val(id);
    $("#" + selectorId).val(name);
    $('#componentSubject').hide()
}

/**
 * 筛选区域 收起，展开
 */
function cutOut(e) {
    let form = $(e).parents("form")
    if (form.find(".more-container").is(":hidden")) {
        form.find(".more-container").show(); //如果元素为隐藏,则将它显现
        $(e).html('收起')
    } else {
        form.find(".more-container").hide(); //如果元素为显现,则将其隐藏
        $(e).html('展开')
    }
}

/**
 * 批量打印
 * @param cla 类
 * @param fun 方法
 * @param formName 表单名
 * @returns {*|jQuery|HTMLElement}
 */
function batchPrint(cla, fun = 'batchPrint', formName = 'listForm') {
    const arrar = []
    let lists = ''
    $("input:checkbox[name='listId[]']:checked").each(function () {
        arrar.push($(this).val())
    })
    lists = arrar.join(',')
    if (lists.length <= 0) {
        return msg('请选择你要打印的单据')
    } else {
        window.open(root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun + '&lists=' + window.btoa(lists))
    }
}


/**
 * 保存临时内容
 * @param cla
 * @param fun
 */
function saveTemp(cla, fun = 'edit', formName = 'EditForm') {
    const formData = $('[name="' + formName + '"]').serialize()
    const data = {
        'cla': cla,
        'fun': fun,
        'body': formData,
    }
    $.post(root + 'control/adIndex.html?cla=homepage&fun=saveTemp', data, function (res) {
        if (res.warn === 2) {
            window.location.reload()
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

function getTemp(cla, fun = 'edit', formName = 'EditForm') {
    $.post(root + 'control/adIndex.html?cla=homepage&fun=getTemp', {'cla': cla, 'fun': fun}, function (res) {
        console.log()
        if (res.warn === 2) {
            if (Object.keys(res.data).length > 0) {
                cxDialog('当前记录存在草稿信息，是否加载?', function () {
                    const formData = res.data
                    $.each(formData, function (key, val) {
                        $("[name=" + formName + "]").find('[name="' + key + '"]').val(val)
                    })
                }, function () {
                })
            }
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

//form支持多表单提交，中间用,隔开，url为提交地址
function subFormVerify(form, url, verifyUrl) {
    let con = setTimeout(function (){
        $("#loading", parent.document).hide();
    },lib_configurg.loading_time_out);
    $("#loading", parent.document).show();
    //串联表单
    var formName = form.split(",");
    var forms = [];
    for (var i = 0; i < formName.length; i++) {
        if (formName[i] !== "") {
            forms =  forms.concat($("[name=" + formName[i] + "]"));
        }
    }
    var jsonData = getFormJson(forms);
    var obj = event.target;//发生点击事件的当前html节点
    //异步提交数据
    $.post(verifyUrl, {serialize_json:JSON.stringify(jsonData)}, function (data) {
        if (data.warn === 2 || data.warn === '2') {
            subForm(form, url)
        } else {
            if(data.allow === 1 || data.allow === '1'){
                cxDialog(data.warn, () => {
                    subForm(form, url)
                }, () => {
                    // click no callback
                });
            }else {
                cxDialog(data.warn,false, () => {
                    // click no callback
                });
            }
        }
        $("#loading", parent.document).hide();
        clearTimeout(con);
    }, "json");
}


/**
 * 删除上传进度
 * @param e
 * @param id
 */
function uploadAborted(e, id) {
    $.post(root + 'control/adIndex.html?cla=share&fun=uploadAborted', {id}, function (res) {
        if (res.warn === 2) {
            $(e).parents('tr').remove()
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

/**
 * 上传分片
 * @param file
 * @param info
 * @param url
 */
function uploadChunks(file, info, url) {
    const chunkSize = 5 * 1024 * 1024;
    const name = file.name;
    const size = file.size;
    const chunks = Math.ceil(size / chunkSize);
    let chunk = info.chunk * 1;

    const start = chunk * chunkSize;
    const end = Math.min(start + chunkSize, size);
    const chunkData = file.slice(start, end);
    const formData = new FormData();
    formData.append('file', chunkData);
    formData.append('name', name);
    formData.append('size', size);
    formData.append('chunks', chunks);
    chunk += 1;
    formData.append('chunk', chunk);
    formData.append('info', JSON.stringify(info));
    info.chunk = chunk
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function (data) {
            if (data.warn == 1) {
                return false
            } else if (data.warn == 2) {
                $('#' + info.id).css('width', data.progress + '%')
                $('.' + info.id + '-scale').text(data.progress + '%')
                if (data.state == 1) {
                    //获取查询结果区域的ID号
                    var searchFormId = 'homeSearchHtml';
                    //更新查询结果
                    var pageNow = $('[searchFormHtml=' + searchFormId + '] > .pageButton .pageNow');//当前页
                    if (pageNow.length == 1) {//如果存在分页
                        pageNow.click();
                    } else {
                        $('[searchFormHtml=' + searchFormId + ']').siblings('.search').find('input[type=submit]').click();
                    }
                    //关闭当前编辑弹窗
                    //$(obj).parents('.win').find('.winClose').click();
                    if (data.msg) {
                        msg(data.msg, 'info')
                    }
                    if ($.cookie('warn')) {
                        warn($.cookie('warn'));
                        $.cookie('warn', '');
                    }
                } else if (chunk < chunks) {
                    uploadChunks(file, info, url);
                }
            } else {
                msg(data.warn, 'error')
            }
        },
        error: function () {
            msg('上传失败', 'error')
        }
    });
}
